import { useRef } from "react";
import styles from "./index.module.less";
import { ProForm, ProFormInstance, ProFormText, ProFormTextArea, ProFormRadio	 } from "@ant-design/pro-components";
import { Affix, Button, ConfigProvider, Flex, Space, message } from "antd";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { emojiRegex, newlineRegex } from "@/pages/product/Create";
import Upload from "@/components/Upload";
import { addBook, editBook, getBookDetail } from "@/api/modules/bookshelf";
import { useRequest } from "ahooks";
import { useEffect } from "react";

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate, query } = useUrl();
	const book_id = query.get("book_id");

	const { loading: loadingDetail, runAsync: getDetailAsync, data: bookDetailInfo } = useRequest(getBookDetail, { manual: true });

	useEffect(() => {
		if (!book_id) return;
		getDetailAsync({ book_id }).then((res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data ?? {};
				const InitialData = {
					...data
				};
				formRef.current?.setFieldsValue(InitialData);
			}
		});
	}, []);

	const handleValuesChange = (changeValue: any) => {
		if (Object.hasOwn(changeValue, "course_name") && typeof changeValue.course_name === "string") {
			const newName = changeValue.course_name.replace(emojiRegex, "").replace(newlineRegex, "");
			formRef.current?.setFieldValue("course_name", newName);
		}
	};

	const handleSubmit = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		const requestData = {
			...values,
			desc: values.introduce
		};
		const callback = () => {
			if (!book_id) {
				// 新增
				addBook(requestData).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("保存成功");
						handleBack();
					}
				});
			} else {
				// 编辑
				editBook({ ...requestData, book_id }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("保存成功");
						handleBack();
					}
				});
			}
		};
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			callback();
		});
	};

	const handleBack = () => {
		navigate("/bookshelf/list");
	};

	return (
		<ConfigProvider
			theme={{
				components: {
					Radio: {
						wrapperMarginInlineEnd: 60
					},
					Checkbox: {
						marginXS: 60,
						borderRadiusSM: 50
					}
				}
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={styles.container}>
					<ProForm
						colon={false}
						submitter={false}
						formRef={formRef}
						layout="horizontal"
						onValuesChange={handleValuesChange}
						labelCol={{ span: 4 }}
					>
						<div className={styles.content_wrap}>
							<div className={styles.content}>
								<div style={{ height: "32px", marginBottom: "12px" }}>
									<div className={styles.title}>{book_id ? "修改书籍" : "新增书籍"}</div>
								</div>
								<ProFormText
									label="书籍名称"
									name="book_name"
									rules={[
										{ required: true, message: "请输入书籍名称" },
										{ max: 12, message: "字数限制12个以内" }
									]}
									placeholder={"最多允许输入12个汉字"}
									fieldProps={{
										showCount: { formatter: ({ count, maxLength }) => `${count}/${maxLength}` }, // 自定义格式
										maxLength: 12
									}}
									extra={<div>标题中请勿使用表情符号、换行符号。</div>}
								/>
								<ProFormText
									label="作者"
									name="book_author"
									rules={[{ required: true, message: "请输入作者名字" }]}
									placeholder={"请输入作者名字"}
								/>
								<ProFormText
									label="字数"
									name="article_num"
									rules={[{ required: true, message: "请输入字数" }]}
									placeholder={"请输入字数"}
									fieldProps={{
										addonAfter: "字"
									}}
								/>
								<ProFormText
									label="福贝值"
									name="points"
									rules={[{ required: true, message: "请输入福贝值" }]}
									placeholder={"请输入福贝值"}
								/>
								<ProForm.Item
									label="封面"
									name="cover_image"
									rules={[{ required: true, message: "请上传书籍封面" }]}
									transform={(v, name) => ({
										[name]: v?.[0]?.url
									})}
								>
									<Upload maxSize={1} canRemove={true} />
								</ProForm.Item>
								<ProFormTextArea
									label="书简介"
									name="introduce"
									rules={[
										{ required: true, message: "请输入书籍简介" },
										{ max: 300, message: "描述不能超过 300 个字符" }
									]}
									placeholder={"请输入书籍简介"}
									fieldProps={{
										showCount: { formatter: ({ count, maxLength }) => `${count}/${maxLength}` }, // 自定义格式
										maxLength: 300,
										autoSize: { minRows: 3, maxRows: 6 } // 自动调整高度
									}}
								/>
								<ProFormRadio.Group
									name="is_listen"
									label="是否支持听书"
									initialValue={0}
									options={[
										{ label: "支持", value: 1 },
										{ label: "不支持", value: 0 }
									]}
								/>
							</div>
						</div>
					</ProForm>
					<Affix offsetBottom={0}>
						<Flex justify="center" className={styles.btns}>
							<Space size={10}>
								<Button ghost type="primary" onClick={() => navigate(-1)}>
									返回
								</Button>
								<Button type="primary" onClick={handleSubmit}>
									保存
								</Button>
							</Space>
						</Flex>
					</Affix>
				</div>
			</Loading>
		</ConfigProvider>
	);
};
